package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

import static android.view.View.GONE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

public class PullActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnFocusChangeListener {
    String TAG=PullActivity.class.getName();
    private static final int MSG_RefreshData=101;
    private static final int msgFocusBarcode=9000;
    private static final int MSG_MAIN=9001;
    private static final int MSG_COLORLIST=9002;
    private static final int MSG_PULLLIST=9003;
    private static final int MSG_PROCRESULT=9004;
    private static final int MSG_PARTLIST=9005;
    private static final int MSG_BEDNO=9006;
    private static final int MSG_ERRMSG=9007;
    private static final int MSG_SCANOVER=9008;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID,BoardNo="";
    String ProduceMasterID="",ProduceCutMaID ="",MakeState="";
    //界面控件
    ListView colorList, pullList;
    Button btn_Refresh,btn_Close, btn_Delete,btn_Edit,btn_Submit,btn_pullvalue_AddLine,btn_SelectPart,btn_NewCutBed;
    TextView text_pull_orderno,text_pull_styleno, text_pull_stylesort,text_pullvalue_total;
    TextView text_pullhead_size1,text_pullhead_size2,text_pullhead_size3,text_pullhead_size4,text_pullhead_size5,text_pullhead_size6,text_pullhead_size7,text_pullhead_size8,
            text_pullhead_size9,text_pullhead_size10,text_pullhead_size11,text_pullhead_size12,text_pullhead_size13,text_pullhead_size14,text_pullhead_size15;
    EditText edit_pullvalue_Color,edit_pullvalue_BowlNo, edit_pullvalue_IdentLen, edit_pullvalue_LevelNum, edit_pullvalue_OwenLen, edit_pullvalue_PrepNum,edit_pullvalue_RollNum,edit_pullvalue_ShortLen;
    EditText edit_pullvalue_size1,edit_pullvalue_size2,edit_pullvalue_size3,edit_pullvalue_size4,edit_pullvalue_size5,edit_pullvalue_size6,
            edit_pullvalue_size7,edit_pullvalue_size8,edit_pull_bedno,edit_pull_bedindex,edit_pullvalue_size9,edit_pullvalue_size10,edit_pullvalue_size11,edit_pullvalue_size12,edit_pullvalue_size13,edit_pullvalue_size14,edit_pullvalue_size15;
    EditText edit_ClothBarcode,edit_pullvalue_PullPeople;
    RadioButton chk_PullTypeA,chk_PullTypeB;
    //用于与主Activity通讯;
    private Handler mainHandler;
    private JSONArray headJSON,titleJson, colorJson,pullJson,procRstJSON,partJson,barcodeJson;//用于存储WebService返回的结果;
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;
    String curLevelNo, curProduceCutDeID,curProduceDetailID,curColor,curColorNo,curPertain,curBedNo,curClothBarcode="";
    //媒体播放文件
    private static MediaPlayer mediaPlayer;
    int curPullListPosition=-1;
    LinearLayout templetlisthead;
    ListView selectTempletList;
    Toast curToast;
    EditText edt_CurSelect;
    String selPartName="";
    private ProgressDialog waitDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pull);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        CPUID=paramBundle.getString("CPUID");
        ProduceCutMaID =paramBundle.getString("ProduceCutMaID");
        ProduceMasterID =paramBundle.getString("ProduceMasterID");
        MakeState =paramBundle.getString("MakeState","");
        System.out.println(paramBundle);
        InitView();
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        CreateDBTable();
        //消息调用刷新数据;
        Message msg=new Message();
        msg.what=MSG_RefreshData;
        handler.removeMessages(MSG_RefreshData);
        handler.sendMessage(msg);
        try {
            titleJson=new JSONArray("[]");
            colorJson=new JSONArray("[]");
            pullJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //创建数据库表
    private void CreateDBTable(){
        if (mainDB!=null) {
            //建表语句;
            mainDB.execSQL("Drop TABLE IF EXISTS PullCloth");
            //员工表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS PullCloth (ID INTEGER PRIMARY KEY AUTOINCREMENT,LevelNo int,ProduceCutDeID VARCHAR,ProduceDetailID VARCHAR,ProduceCutMaID VARCHAR,ColorNo VARCHAR, Color VARCHAR," +
                    "Pertain VARCHAR,BowlNo VARCHAR,IdentLen NUMERIC(8,2),LevelNum Int,PrepNum NUMERIC(8,2),RollNum NUMERIC(8,2),ShortLen NUMERIC(8,2),OwenLen NUMERIC(8,2),PullPeople VARCHAR,PullType VARCHAR,ClothBarcode VARCHAR )");
        }
    }
    //初始化界面
    private void InitView(){
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog= new ProgressDialog(this);
        waitDialog.setTitle(getString(R.string.SystemHint));
        //界面控件
        edit_ClothBarcode=findViewById(R.id.edit_ClothBarcode);
        chk_PullTypeB =findViewById(R.id.chk_PullTypeB);
        chk_PullTypeA =findViewById(R.id.chk_PullTypeA);
        //界面Edit;
        edit_ClothBarcode=(EditText)findViewById(R.id.edit_ClothBarcode);
        edit_ClothBarcode.setInputType(InputType.TYPE_NULL);
        edit_ClothBarcode.setOnFocusChangeListener(this);
        edit_ClothBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        if (edit_ClothBarcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        } else {
                            //执行查询;
                            if (edit_ClothBarcode.getText().toString().length() == 0) {
                                curToast.setText(getString(R.string.PlsSelectRSType));
                                curToast.show();
                            } else{
                                searchBarcodeData(edit_ClothBarcode.getText().toString(),text_pull_orderno.getText().toString(),text_pull_styleno.getText().toString(),text_pull_stylesort.getText().toString());
                            }
                        }
                        //未有焦点
                        if (edit_ClothBarcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        } else edit_ClothBarcode.selectAll();
                    }

                }
                return false;
            }
        });
        edit_ClothBarcode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                edit_ClothBarcode.setInputType(InputType.TYPE_CLASS_TEXT);

                return false;
            }
        });
        edit_ClothBarcode.requestFocus();
        edit_ClothBarcode.requestFocusFromTouch();
        colorList=findViewById(R.id.colorList);
        colorList.setOnItemClickListener(this);
        pullList =findViewById(R.id.pullList);
        pullList.setOnItemClickListener(this);
        btn_Refresh=findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
        btn_Close=findViewById(R.id.btn_Close);
        btn_Close.setOnClickListener(this);
        btn_Delete =findViewById(R.id.btn_Delete);
        btn_Delete.setOnClickListener(this);
        btn_Edit=findViewById(R.id.btn_Edit);
        btn_Edit.setOnClickListener(this);
        btn_Submit=findViewById(R.id.btn_Submit);
        btn_Submit.setOnClickListener(this);
        btn_SelectPart=findViewById(R.id.btn_SelectPart);
        btn_SelectPart.setOnClickListener(this);
        btn_pullvalue_AddLine=findViewById(R.id.btn_pullvalue_AddLine);
        btn_pullvalue_AddLine.setOnClickListener(this);
        btn_NewCutBed=findViewById(R.id.btn_NewCutBed);
        btn_NewCutBed.setOnClickListener(this);
        //各个标签;
        edit_pullvalue_Color=findViewById(R.id.edit_pullvalue_Color);
        edit_pull_bedno =findViewById(R.id.edit_pull_bedno);
        edit_pull_bedindex=findViewById(R.id.edit_pull_bedindex);
        text_pull_orderno=findViewById(R.id.text_pull_orderno);
        text_pull_styleno=findViewById(R.id.text_pull_styleno);
        text_pull_stylesort =findViewById(R.id.text_pull_stylesort);
        text_pullhead_size1=findViewById(R.id.text_pullhead_size1);
        text_pullhead_size2=findViewById(R.id.text_pullhead_size2);
        text_pullhead_size3=findViewById(R.id.text_pullhead_size3);
        text_pullhead_size4=findViewById(R.id.text_pullhead_size4);
        text_pullhead_size5=findViewById(R.id.text_pullhead_size5);
        text_pullhead_size6=findViewById(R.id.text_pullhead_size6);
        text_pullhead_size7=findViewById(R.id.text_pullhead_size7);
        text_pullhead_size8=findViewById(R.id.text_pullhead_size8);
        text_pullhead_size9=findViewById(R.id.text_pullhead_size9);
        text_pullhead_size10=findViewById(R.id.text_pullhead_size10);
        text_pullhead_size11=findViewById(R.id.text_pullhead_size11);
        text_pullhead_size12=findViewById(R.id.text_pullhead_size12);
        text_pullhead_size13=findViewById(R.id.text_pullhead_size13);
        text_pullhead_size14=findViewById(R.id.text_pullhead_size14);
        text_pullhead_size15=findViewById(R.id.text_pullhead_size15);
        edit_pullvalue_BowlNo =findViewById(R.id.edit_pullvalue_BowlNo);
        edit_pullvalue_BowlNo.setOnFocusChangeListener(this);
        edit_pullvalue_IdentLen =findViewById(R.id.edit_pullvalue_IdentLen);
        edit_pullvalue_IdentLen.setOnFocusChangeListener(this);
        edit_pullvalue_LevelNum =findViewById(R.id.edit_pullvalue_LevelNum);
        edit_pullvalue_LevelNum.setOnFocusChangeListener(this);
        edit_pullvalue_ShortLen=findViewById(R.id.edit_pullvalue_ShortLen);
        edit_pullvalue_ShortLen.setOnFocusChangeListener(this);
        edit_pullvalue_OwenLen =findViewById(R.id.edit_pullvalue_OwenLen);
        edit_pullvalue_OwenLen.setOnFocusChangeListener(this);
        edit_pullvalue_PrepNum =findViewById(R.id.edit_pullvalue_PrepNum);
        edit_pullvalue_PrepNum.setOnFocusChangeListener(this);
        edit_pullvalue_RollNum =findViewById(R.id.edit_pullvalue_RollNum);
        edit_pullvalue_RollNum.setOnFocusChangeListener(this);
        edit_pullvalue_PullPeople=findViewById(R.id.edit_pullvalue_PullPeople);
        edit_pullvalue_PullPeople.setOnFocusChangeListener(this);
        edit_pullvalue_PullPeople.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                edit_pullvalue_PullPeople.setText("");
                return false;
            }
        });
        edit_pullvalue_size1=findViewById(R.id.edit_pullvalue_size1);
        edit_pullvalue_size2=findViewById(R.id.edit_pullvalue_size2);
        edit_pullvalue_size3=findViewById(R.id.edit_pullvalue_size3);
        edit_pullvalue_size4=findViewById(R.id.edit_pullvalue_size4);
        edit_pullvalue_size5=findViewById(R.id.edit_pullvalue_size5);
        edit_pullvalue_size6=findViewById(R.id.edit_pullvalue_size6);
        edit_pullvalue_size7=findViewById(R.id.edit_pullvalue_size7);
        edit_pullvalue_size8=findViewById(R.id.edit_pullvalue_size8);
        edit_pullvalue_size9=findViewById(R.id.edit_pullvalue_size9);
        edit_pullvalue_size10=findViewById(R.id.edit_pullvalue_size10);
        edit_pullvalue_size11=findViewById(R.id.edit_pullvalue_size11);
        edit_pullvalue_size12=findViewById(R.id.edit_pullvalue_size12);
        edit_pullvalue_size13=findViewById(R.id.edit_pullvalue_size13);
        edit_pullvalue_size14=findViewById(R.id.edit_pullvalue_size14);
        edit_pullvalue_size15=findViewById(R.id.edit_pullvalue_size15);
        text_pullvalue_total=findViewById(R.id.text_pullvalue_total);
        edit_pullvalue_IdentLen.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                System.out.println("IdentLen-onTextChanged");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                System.out.println("IdentLen-afterTextChanged");
                calcePrepNum();
            }

        });
        edit_pullvalue_RollNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                System.out.println("RollNum-onTextChanged");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                System.out.println("RollNum-onTextChanged");
                calcePrepNum();
            }

        });
        edit_pullvalue_LevelNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                System.out.println("LevelNum-onTextChanged");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                System.out.println("LevelNum-afterTextChanged");
                calcePrepNum();
            }

        });
        edit_pullvalue_OwenLen.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                System.out.println("OwenLen-onTextChanged");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                System.out.println("OwenLen-afterTextChanged");
                calcePrepNum();
            }

        });
    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String OrderNoParam,String StyleNoParam,String StyleSortParam)
    {
        playRingtone();
        curClothBarcode=BarcodeParam;
        edit_ClothBarcode.setInputType(InputType.TYPE_NULL);
        edit_ClothBarcode.setHint(BarcodeParam);
        edit_ClothBarcode.setText("");
        //执行SQL过程
        String SqlComm="Exec KeyPoint_CutClothBarcode @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@StyleSort='" + StyleSortParam+ "',@OPERTYPE='SCANBARCODE',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    //计算余布;
    private void calcePrepNum() {
        System.out.println("calcePrepNum--Enter");
        System.out.println(edit_pullvalue_IdentLen.getText().toString());
        System.out.println(edit_pullvalue_RollNum.getText().toString());
        System.out.println(edit_pullvalue_LevelNum.getText().toString());
        System.out.println(isNumer(edit_pullvalue_IdentLen.getText().toString()));
        System.out.println(isNumer(edit_pullvalue_RollNum.getText().toString()));
        System.out.println(isNumer(edit_pullvalue_LevelNum.getText().toString()));
        if (isNumer(edit_pullvalue_IdentLen.getText().toString())==true
                &&isNumer(edit_pullvalue_RollNum.getText().toString())==true
                &&isNumer(edit_pullvalue_LevelNum.getText().toString())==true)
        {
            System.out.println("calcePrepNum--Trans");
            float identLen=Float.parseFloat(edit_pullvalue_IdentLen.getText().toString());
            float rollNum=Float.parseFloat(edit_pullvalue_RollNum.getText().toString());
            float levelNum=Float.parseFloat(edit_pullvalue_LevelNum.getText().toString());
            float owenLen=0;
            if (isNumer(edit_pullvalue_OwenLen.getText().toString())==true)
                owenLen=Float.parseFloat(edit_pullvalue_OwenLen.getText().toString());
            else
                owenLen=0;
            float shortLen=identLen-rollNum*levelNum-owenLen;
            edit_pullvalue_ShortLen.setText(String.valueOf(shortLen));
        }
    }


    //获取数据;
    private void ReGetData(String paramProduceMasterID,String paramCutMaID,String paramOperType){
        //置值
        String SqlComm="Exec KeyPoint_CutGetData  @ProduceMasterID='"+paramProduceMasterID+"',@ProduceCutMaID='"+paramCutMaID+"',@OperatorNo='"+curLoginUserNo+"',@OperType='"+paramOperType+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_SCANOVER:
                    fillCloth(barcodeJson);
                    setEditBarcodeFocus();
                    break;
                case msgFocusBarcode:
                    setEditBarcodeFocus();
                    break;
                case MSG_ERRMSG:
                    Bundle bundle=msg.getData();
                    curToast.setText(bundle.getString("MSG"));
                    curToast.show();
                    break;
                case MSG_RefreshData:
                    btn_Refresh.performClick();
                    break;
                case MSG_MAIN:
                    fillText();
                    break;
                case MSG_BEDNO:
                    edit_pull_bedno.setText(curBedNo);
                    break;
                case MSG_PARTLIST:
                    break;
                case MSG_PULLLIST:
                    //通过适配器显示;
                    PullListAdapter pullListAdapter=new PullListAdapter(getApplicationContext());
                    pullList.setAdapter(pullListAdapter);
                    showClothFootTotal();
                    curPullListPosition=-1;
                    break;
                case MSG_COLORLIST:
                    //通过适配器显示;
                    ColorListAdapter colorListAdapter=new ColorListAdapter(getApplicationContext());
                    colorList.setAdapter(colorListAdapter);
                    break;
                case MSG_PROCRESULT:
                    String resultMsg = null;
                    try {
                        if (procRstJSON.optJSONObject(0).has("TransMethod")){
                            String TransMethod=procRstJSON.optJSONObject(0).getString("TransMethod");
                            if (TransMethod.toUpperCase().equals("NewBed".toUpperCase())){
                                clearPullData();
                            }
                        }
                        resultMsg = procRstJSON.optJSONObject(0).getString("PROCRESULT");
                        //提示提交完成，需确认;
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(PullActivity.this)
                                .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                default:
                    break;
            }
        }
    };

    private void fillCloth(JSONArray barcodeJson) {
        if ((barcodeJson!=null)&&(barcodeJson.length()>0)){
            curLevelNo=getLevelNo();
            Log.e(TAG,curLevelNo);
            try {
                curProduceCutDeID= UUID.randomUUID().toString();
                if (barcodeJson.optJSONObject(0).has("ProduceDetailID")) curProduceDetailID=barcodeJson.optJSONObject(0).getString("ProduceDetailID");
                if (barcodeJson.optJSONObject(0).has("Color")) curColor=barcodeJson.optJSONObject(0).getString("Color");
                if (barcodeJson.optJSONObject(0).has("ColorNo")) curColorNo=barcodeJson.optJSONObject(0).getString("ColorNo");
                if (barcodeJson.optJSONObject(0).has("Pertain")) curPertain=barcodeJson.optJSONObject(0).getString("Pertain");
                if (barcodeJson.optJSONObject(0).has("BowlNo")) edit_pullvalue_BowlNo.setText(barcodeJson.optJSONObject(0).getString("BowlNo"));
                if (barcodeJson.optJSONObject(0).has("IdentLen")) edit_pullvalue_IdentLen.setText(barcodeJson.optJSONObject(0).getString("IdentLen"));
                if (barcodeJson.optJSONObject(0).has("PrepNum")) edit_pullvalue_PrepNum.setText(barcodeJson.optJSONObject(0).getString("PrepNum"));
                if (barcodeJson.optJSONObject(0).has("ClothBarcode")) curClothBarcode=barcodeJson.optJSONObject(0).getString("ClothBarcode");
                if (barcodeJson.optJSONObject(0).has("PullPeople")) {
                    String pullPeople=edit_pullvalue_PullPeople.getText().toString();
                    String curPeople=barcodeJson.optJSONObject(0).getString("PullPeople");
                    if (pullPeople.indexOf(curPeople)<0) {
                        if (edit_pullvalue_PullPeople.getText().toString().length() > 0)
                            edit_pullvalue_PullPeople.setText(edit_pullvalue_PullPeople.getText().toString() + "," + barcodeJson.optJSONObject(0).getString("PullPeople"));
                        else
                            edit_pullvalue_PullPeople.setText(barcodeJson.optJSONObject(0).getString("PullPeople"));
                    }
                }
                if (barcodeJson.optJSONObject(0).has("RollNum")) {
                    edit_pullvalue_RollNum.setText(barcodeJson.optJSONObject(0).getString("RollNum"));
                    setActiveEdt(edit_pullvalue_LevelNum);
                } else   setActiveEdt(edit_pullvalue_RollNum);
                ((TextView)findViewById(R.id.edit_pullvalue_Color)).setText(curColor);
                ((TextView)findViewById(R.id.edit_pullvalue_ColorNo)).setText(curColorNo);
                ((TextView)findViewById(R.id.edit_pullvalue_Pertain)).setText(curPertain);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            btn_pullvalue_AddLine.setText("添加行");
            btn_pullvalue_AddLine.setBackgroundColor(getResources().getColor(R.color.text_orange));
        }

    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    String OperType="";
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            return;
                        }
                        //System.out.println(jsonArray);
                        //呼叫信息及库存警告
                        if (OperType.toUpperCase().equals("MAIN")==true)
                        {
                            //往界面转数据;
                            titleJson=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_MAIN;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);

                        }
                        if (OperType.toUpperCase().equals("SCANBARCODE")==true)
                        {
                            barcodeJson =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_SCANOVER;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);

                        }
                        if (OperType.toUpperCase().equals("COLORLIST")==true)
                        {
                            colorJson =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_COLORLIST;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);

                        }
                        if (OperType.toUpperCase().equals("PARTLIST")==true)
                        {
                            partJson =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_PARTLIST;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);

                        }
                        if (OperType.toUpperCase().equals("PULLLIST")==true)
                        {
                            pullJson =jsonArray;
                            //保存到数据库中
                            mainDB.execSQL("Delete from PullCloth");
                            for (int i=0;i<pullJson.length();i++) {
                                mainDB.execSQL("INSERT INTO PullCloth(LevelNo,ProduceCutDeID,ProduceDetailID,ProduceCutMaID,ColorNo,Color,Pertain,BowlNo,IdentLen,LevelNum,PrepNum,RollNum,OwenLen,PullPeople,ClothBarcode) " +
                                                "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                        new Object[]{pullJson.optJSONObject(i).getString("LevelNo"), pullJson.optJSONObject(i).getString("ProduceCutDeID")
                                                , pullJson.optJSONObject(i).getString("ProduceDetailID"), pullJson.optJSONObject(i).getString("ProduceCutMaID")
                                                , pullJson.optJSONObject(i).getString("ColorNo"), pullJson.optJSONObject(i).getString("Color")
                                                , pullJson.optJSONObject(i).getString("Pertain"), pullJson.optJSONObject(i).getString("BowlNo")
                                                , pullJson.optJSONObject(i).get("IdentLen"), pullJson.optJSONObject(i).get("LevelNum")
                                                , pullJson.optJSONObject(i).get("PrepNum"), pullJson.optJSONObject(i).get("RollNum"), pullJson.optJSONObject(i).get("OwenLen")
                                                , pullJson.optJSONObject(i).get("PullPeople"), pullJson.optJSONObject(i).get("ClothBarcode")

                                        });
                            }
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_PULLLIST;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);

                        }
                        //呼叫信息及库存警告
                        if (OperType.toUpperCase().equals("BEDNO")==true)
                        {
                            curBedNo=jsonArray.optJSONObject(0).getString("BedNo");
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_BEDNO;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (jsonArray.getJSONObject(0).has("PROCRESULT")==true) {
                            procRstJSON=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_PROCRESULT;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);

                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            return;
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }

    //填充界面
    private void fillText() {
        if (titleJson!=null) {
            if (titleJson.length()>0){
                JSONObject tmp=titleJson.optJSONObject(0);
                if (tmp!=null) {
                    try {
                        if (tmp.has("ProduceMasterID")==true) ProduceMasterID=tmp.getString("ProduceMasterID");
                        if (tmp.has("ProduceCutMaID")==true) ProduceCutMaID=tmp.getString("ProduceCutMaID");
                        if (tmp.has("OrderNo")==true) text_pull_orderno.setText(TransValue(tmp.getString("OrderNo")));
                        if (tmp.has("StyleNo")==true) text_pull_styleno.setText(TransValue(tmp.getString("StyleNo")));
                        if (tmp.has("StyleSort")==true) text_pull_stylesort.setText(TransValue(tmp.getString("StyleSort")));
                        if (tmp.has("BedNo")==true) edit_pull_bedno.setText(TransValue(tmp.getString("BedNo")));
                        if (tmp.has("BedIndex")==true) edit_pull_bedindex.setText(TransValue(tmp.getString("BedIndex")));
                        if (tmp.has("PartName")==true) btn_SelectPart.setText(TransValue(tmp.getString("PartName")));
                        if (tmp.has("Size1")==true) text_pullhead_size1.setText(TransValue(tmp.getString("Size1")));
                        if (tmp.has("Size2")==true) text_pullhead_size2.setText(TransValue(tmp.getString("Size2")));
                        if (tmp.has("Size3")==true) text_pullhead_size3.setText(TransValue(tmp.getString("Size3")));
                        if (tmp.has("Size4")==true) text_pullhead_size4.setText(TransValue(tmp.getString("Size4")));
                        if (tmp.has("Size5")==true) text_pullhead_size5.setText(TransValue(tmp.getString("Size5")));
                        if (tmp.has("Size6")==true) text_pullhead_size6.setText(TransValue(tmp.getString("Size6")));
                        if (tmp.has("Size7")==true) text_pullhead_size7.setText(TransValue(tmp.getString("Size7")));
                        if (tmp.has("Size8")==true) text_pullhead_size8.setText(TransValue(tmp.getString("Size8")));
                        if (tmp.has("Size9")==true) text_pullhead_size9.setText(TransValue(tmp.getString("Size9")));
                        if (tmp.has("Size10")==true) text_pullhead_size10.setText(TransValue(tmp.getString("Size10")));
                        if (tmp.has("Size11")==true) text_pullhead_size11.setText(TransValue(tmp.getString("Size11")));
                        if (tmp.has("Size12")==true) text_pullhead_size12.setText(TransValue(tmp.getString("Size12")));
                        if (tmp.has("Size13")==true) text_pullhead_size13.setText(TransValue(tmp.getString("Size13")));
                        if (tmp.has("Size14")==true) text_pullhead_size14.setText(TransValue(tmp.getString("Size14")));
                        if (tmp.has("Size15")==true) text_pullhead_size15.setText(TransValue(tmp.getString("Size15")));

                        if (tmp.has("iSize1")==true) edit_pullvalue_size1.setText(TransValue(tmp.getString("iSize1")));
                        if (tmp.has("iSize2")==true) edit_pullvalue_size2.setText(TransValue(tmp.getString("iSize2")));
                        if (tmp.has("iSize3")==true) edit_pullvalue_size3.setText(TransValue(tmp.getString("iSize3")));
                        if (tmp.has("iSize4")==true) edit_pullvalue_size4.setText(TransValue(tmp.getString("iSize4")));
                        if (tmp.has("iSize5")==true) edit_pullvalue_size5.setText(TransValue(tmp.getString("iSize5")));
                        if (tmp.has("iSize6")==true) edit_pullvalue_size6.setText(TransValue(tmp.getString("iSize6")));
                        if (tmp.has("iSize7")==true) edit_pullvalue_size7.setText(TransValue(tmp.getString("iSize7")));
                        if (tmp.has("iSize8")==true) edit_pullvalue_size8.setText(TransValue(tmp.getString("iSize8")));
                        if (tmp.has("iSize9")==true) edit_pullvalue_size9.setText(TransValue(tmp.getString("iSize9")));
                        if (tmp.has("iSize10")==true) edit_pullvalue_size10.setText(TransValue(tmp.getString("iSize10")));
                        if (tmp.has("iSize11")==true) edit_pullvalue_size11.setText(TransValue(tmp.getString("iSize11")));
                        if (tmp.has("iSize12")==true) edit_pullvalue_size12.setText(TransValue(tmp.getString("iSize12")));
                        if (tmp.has("iSize13")==true) edit_pullvalue_size13.setText(TransValue(tmp.getString("iSize13")));
                        if (tmp.has("iSize14")==true) edit_pullvalue_size14.setText(TransValue(tmp.getString("iSize14")));
                        if (tmp.has("iSize15")==true) edit_pullvalue_size15.setText(TransValue(tmp.getString("iSize15")));
                        if (tmp.has("Total")==true) text_pullvalue_total.setText(TransValue(tmp.getString("Total")));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }


    public  String TransValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }

    private void setActiveEdt(EditText paramEditText) {
        EditText editText = edt_CurSelect;
        if (editText != null)
            editText.setBackground(getResources().getDrawable(R.drawable.frameline_background));
        edt_CurSelect = paramEditText;
        edt_CurSelect.setBackgroundColor(getResources().getColor(R.color.skyblue));
        edt_CurSelect.setFocusable(true);
        edt_CurSelect.setFocusableInTouchMode(true);
        edt_CurSelect.requestFocusFromTouch();
        edt_CurSelect.requestFocus();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_NewCutBed:
                ProduceCutMaID = UUID.randomUUID().toString();
                ((TextView)findViewById(R.id.edit_pullvalue_Color)).setText("");
                ((TextView)findViewById(R.id.edit_pullvalue_ColorNo)).setText("");
                ((TextView)findViewById(R.id.edit_pullvalue_Pertain)).setText("");
                edit_pullvalue_BowlNo.setText("");
                edit_pullvalue_IdentLen.setText("");
                edit_pullvalue_LevelNum.setText("");
                edit_pullvalue_PrepNum.setText("");//门幅
                edit_pullvalue_RollNum.setText("");//段长
                edit_pullvalue_OwenLen.setText("");
                edit_pullvalue_ShortLen.setText("");
                edit_pullvalue_size1.setText("");
                edit_pullvalue_size2.setText("");
                edit_pullvalue_size3.setText("");
                edit_pullvalue_size4.setText("");
                edit_pullvalue_size5.setText("");
                edit_pullvalue_size6.setText("");
                edit_pullvalue_size7.setText("");
                edit_pullvalue_size8.setText("");
                edit_pullvalue_size9.setText("");
                edit_pullvalue_size10.setText("");
                edit_pullvalue_size11.setText("");
                edit_pullvalue_size12.setText("");
                edit_pullvalue_size13.setText("");
                edit_pullvalue_size14.setText("");
                edit_pullvalue_size15.setText("");
                clearPullData();
                break;
            case R.id.btn_SelectPart:
                if (partJson!=null) showSelectPart();else
                    ReGetData(ProduceMasterID,ProduceCutMaID, "PARTLIST");
                break;
            case R.id.btn_pullvalue_AddLine:
                if (btn_pullvalue_AddLine.getText().equals("添加行")) addLine(0,true);
                else  addLine(curPullListPosition,false);
                break;
            case R.id.btn_Refresh:
                ReGetData(ProduceMasterID, ProduceCutMaID,"MAIN");
                ReGetData(ProduceMasterID,ProduceCutMaID,"COLORLIST");
                ReGetData(ProduceMasterID,ProduceCutMaID, "PULLLIST");
                ReGetData(ProduceMasterID,ProduceCutMaID, "PARTLIST");
                break;
            case R.id.btn_Close:
                finish();
                break;
            case R.id.btn_Edit:
                System.out.println("btn_Edit");
                if (MakeState.equals("READY")==true){
                    curToast.setText("已生成床次不能被编辑！");
                    curToast.show();
                    return;
                }
                if ((curPullListPosition>-1)&&(curPullListPosition<pullJson.length())) {
                    //showPullLevel(curPullListPosition,false);
                    try {
                        edit_pullvalue_BowlNo.setText( pullJson.optJSONObject(curPullListPosition).getString("BowlNo"));
                        edit_pullvalue_IdentLen.setText( pullJson.optJSONObject(curPullListPosition).getString("IdentLen"));
                        edit_pullvalue_LevelNum.setText( pullJson.optJSONObject(curPullListPosition).getString("LevelNum"));
                        edit_pullvalue_PrepNum.setText( pullJson.optJSONObject(curPullListPosition).getString("PrepNum"));
                        edit_pullvalue_RollNum.setText( pullJson.optJSONObject(curPullListPosition).getString("RollNum"));
                        edit_pullvalue_OwenLen.setText( pullJson.optJSONObject(curPullListPosition).getString("OwenLen"));
                        edit_pullvalue_PullPeople.setText( pullJson.optJSONObject(curPullListPosition).getString("PullPeople"));
                        curClothBarcode=pullJson.optJSONObject(curPullListPosition).getString("ClothBarcode");
                        ((TextView)findViewById(R.id.edit_pullvalue_Color)).setText(pullJson.optJSONObject(curPullListPosition).getString("Color"));
                        ((TextView)findViewById(R.id.edit_pullvalue_ColorNo)).setText(pullJson.optJSONObject(curPullListPosition).getString("ColorNo"));
                        ((TextView)findViewById(R.id.edit_pullvalue_Pertain)).setText(pullJson.optJSONObject(curPullListPosition).getString("Pertain"));
                        btn_pullvalue_AddLine.setText("更新行");
                        btn_pullvalue_AddLine.setBackgroundColor(getResources().getColor(R.color.text_green));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    curToast.setText("请选择需要的编辑的行!");
                    curToast.show();
                }
                break;
            case R.id.btn_Delete:
                if (MakeState.equals("READY")==true){
                    curToast.setText("已生成床次不能被编辑！");
                    curToast.show();
                    return;
                }
                System.out.println("btn_Delete");
                if ((curPullListPosition>-1)&&(curPullListPosition<pullJson.length()))
                {
                    try {
                        curProduceCutDeID=pullJson.optJSONObject(curPullListPosition).getString("ProduceCutDeID");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle("系统提示").setMessage("你确定要删除选中的拉布信息吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    pullJson.remove(curPullListPosition);
                                    mainDB.execSQL("Delete from PullCloth where ProduceCutDeID=?",new String[]{curProduceCutDeID});
                                    //更新显示;
                                    ((BaseAdapter)pullList.getAdapter()).notifyDataSetChanged();
                                    showClothFootTotal();
                                }
                            }).setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框

                }else {
                    curToast.setText("请选择需要的删除的行!");
                    curToast.show();
                }
                break;
            case R.id.btn_Submit:
                System.out.println("btn_Submit");
                if (MakeState.equals("READY")==true){
                    curToast.setText("已生成床次不能被编辑！");
                    curToast.show();
                    return;
                }
                if ((pullJson==null)||(pullJson.length()==0)) {
                    curToast.setText("数据为空，不能提交!");
                    curToast.show();
                    return;
                }
                SavePullDetail();
                break;
            default:
                break;
        }

    }


    //显示工序选择
    private void showSelectPart(){
        if (partJson==null) {
            return;
        }
        try {
            headJSON=new JSONArray("[{TitleName:'PartName','TitleText':'部件','TxtSize':18,'TxtWidth':150,'AutoZoom':1,'Align':0,'Colo':'Blue'}]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="部件选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        templetlisthead.setVisibility(GONE);
        //创建表头;
        CreateListHead();
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                if (partJson.optJSONObject(position).has("PartName"))
                try {
                    selPartName=partJson.optJSONObject(position).getString("PartName");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(this);
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if ((selPartName!=null)&&(selPartName.length()>0)) {
                            //填充并过滤
                            btn_SelectPart.setText(selPartName);
                            btn_SelectPart.setBackgroundColor(getResources().getColor(R.color.text_main));
                            GetBedNo(selPartName);
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        } else{
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();

                        }
                    }

                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selPartName="";
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 400;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
    }

    private void GetBedNo(String selPartName) {
        //置值
        String SqlComm="Exec KeyPoint_CutGetData  @ProduceMasterID='"+ProduceMasterID+"',@ProduceCutMaID='"+ProduceCutMaID+"',@PartName='"+selPartName+"',@OperatorNo='"+curLoginUserNo+"',@OperType='BEDNO'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


    //判断是否为数字
    public static boolean isNumer(String str) {
        try {
            if (str.length() == 0) return false;
            for (int i = str.length(); --i >= 0; ) {
                if (!Character.isDigit(str.charAt(i))) {
                    return false;
                }
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }
    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if (view.getClass()==EditText.class){
            if (b==true) setActiveEdt((EditText) view);
        }
    }


    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return partJson.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<partJson.length())
                    return partJson.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<partJson.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (partJson.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = partJson.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (partJson.optJSONObject(curPosition).has(TitleName)==true) tmpValue= partJson.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }
    //提交所选择的工序至服务器,然后刷新工序列表;
    private void SavePullDetail() {
        System.out.println("SavePullDetail");
        if (btn_SelectPart.getText().toString().equals("选择部件")){
            Toast.makeText(getApplicationContext(), "请选择部件!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (chk_PullTypeA.isChecked()==false&&chk_PullTypeB.isChecked()==false) {
            curToast.setText("请先选择裁床类别！");
            curToast.show();
            return;
        }
        if (pullJson==null) return;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String ScenePullMaID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = ToolUtil.getSQLConnection().prepareStatement(
                            "Insert into ScenePullDe(ScenePullDeID,ScenePullMaID,ProduceCutDeID,ProduceDetailID,LevelNo,BowlNo,IdentLen,LevelNum,PrepNum,RollNum,ShortLen,OwenLen,PullPeople,PullType,ClothBarcode)" +
                                    "values(newid(),?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                    //增加明细表
                    for (int i = 0; i < pullJson.length(); i++) {
                        if (pullJson.getJSONObject(i).has("LevelNum") == true) {
                            if (pullJson.getJSONObject(i).getString("LevelNum").length() > 0) {
                                pstmt.setString(1, ScenePullMaID);
                                pstmt.setString(2, pullJson.getJSONObject(i).getString("ProduceCutDeID"));
                                pstmt.setString(3, pullJson.getJSONObject(i).getString("ProduceDetailID"));
                                //pstmt.setString(4, pullJson.getJSONObject(i).getString("LevelNo"));
                                pstmt.setString(4, String.valueOf(i+1));
                                pstmt.setString(5, pullJson.getJSONObject(i).getString("BowlNo"));
                                pstmt.setString(6, pullJson.getJSONObject(i).getString("IdentLen"));
                                pstmt.setString(7, pullJson.getJSONObject(i).getString("LevelNum"));
                                pstmt.setString(8, pullJson.getJSONObject(i).getString("PrepNum"));
                                pstmt.setString(9, pullJson.getJSONObject(i).getString("RollNum"));
                                pstmt.setString(10,pullJson.getJSONObject(i).getString("ShortLen"));
                                pstmt.setString(11, pullJson.getJSONObject(i).getString("OwenLen"));
                                pstmt.setString(12, pullJson.getJSONObject(i).getString("PullPeople"));
                                pstmt.setString(13, pullJson.getJSONObject(i).getString("PullType"));
                                if (pullJson.getJSONObject(i).has("ClothBarcode"))  pstmt.setString(14, pullJson.getJSONObject(i).getString("ClothBarcode"));
                                else  pstmt.setString(14,"UNKNOW");
                                pstmt.executeUpdate();
                            }
                        }
                    }
                    pstmt.close();
                    //增加主表;
                    pstmt = ToolUtil.getSQLConnection().prepareStatement(
                            "Insert into ScenePullMa(ScenePullMaID,ProduceMasterID,ProduceCutMaID,MarkDeID,Department,Operator,BedNo,BedIndex,PartName,Size1,Size2,Size3,Size4,Size5,Size6,Size7,Size8,Size9,Size10,Size11,Size12,Size13,Size14,Size15,UserNo,CreateTime,PullType)" +
                                    " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,getdate(),?)");
                    pstmt.setString(1, ScenePullMaID);
                    pstmt.setString(2, ProduceMasterID);
                    pstmt.setString(3, ProduceCutMaID);
                    pstmt.setString(4, null);
                    pstmt.setString(5, null);
                    pstmt.setString(6, null);
                    pstmt.setString(7, edit_pull_bedno.getText().toString());
                    pstmt.setString(8, edit_pull_bedindex.getText().toString());
                    pstmt.setString(9, btn_SelectPart.getText().toString());
                    pstmt.setString(10, edit_pullvalue_size1.getText().toString());
                    pstmt.setString(11, edit_pullvalue_size2.getText().toString());
                    pstmt.setString(12, edit_pullvalue_size3.getText().toString());
                    pstmt.setString(13, edit_pullvalue_size4.getText().toString());
                    pstmt.setString(14, edit_pullvalue_size5.getText().toString());
                    pstmt.setString(15, edit_pullvalue_size6.getText().toString());
                    pstmt.setString(16, edit_pullvalue_size7.getText().toString());
                    pstmt.setString(17, edit_pullvalue_size8.getText().toString());
                    pstmt.setString(18, edit_pullvalue_size9.getText().toString());
                    pstmt.setString(19, edit_pullvalue_size10.getText().toString());
                    pstmt.setString(20, edit_pullvalue_size11.getText().toString());
                    pstmt.setString(21, edit_pullvalue_size12.getText().toString());
                    pstmt.setString(22, edit_pullvalue_size13.getText().toString());
                    pstmt.setString(23, edit_pullvalue_size14.getText().toString());
                    pstmt.setString(24, edit_pullvalue_size15.getText().toString());
                    pstmt.setString(25, curLoginUserNo);
                    if (chk_PullTypeB.isChecked()==true) pstmt.setString(26, "Auto");
                    else pstmt.setString(26, "Hand");
                    pstmt.executeUpdate();
                    pstmt.close();
                    //调用存储过程;
                    SqlComm = " Exec ScenePAD_TransScenePull @ScenePullMaID='" + ScenePullMaID + "'";
                    ReadSQLData(SqlComm);
                } catch (JSONException e) {
                    e.printStackTrace();
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                } catch (SQLException e) {
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);

                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }
    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edit_ClothBarcode!=null) {
            setActiveEdt(edit_ClothBarcode);
            edit_ClothBarcode.selectAll();
            edit_ClothBarcode.setFocusable(true);
            edit_ClothBarcode.setFocusableInTouchMode(true);
            edit_ClothBarcode.requestFocus();
            edit_ClothBarcode.requestFocusFromTouch();
            hideIM(edit_ClothBarcode);
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.e(TAG,"onItemClick");
        if (parent==colorList)
        {
            if (MakeState.equals("READY")==true){
                curToast.setText("已生成床次不能被编辑！");
                curToast.show();
                return;
            }
            try {
                curLevelNo=getLevelNo();
                Log.e(TAG,curLevelNo);
                curProduceCutDeID= UUID.randomUUID().toString();
                curProduceDetailID=colorJson.optJSONObject(position).getString("ProduceDetailID");
                curColor=colorJson.optJSONObject(position).getString("Color");
                curColorNo=colorJson.optJSONObject(position).getString("ColorNo");
                curPertain=colorJson.optJSONObject(position).getString("Pertain");
                ((TextView)findViewById(R.id.edit_pullvalue_Color)).setText(curColor);
                ((TextView)findViewById(R.id.edit_pullvalue_ColorNo)).setText(curColorNo);
                ((TextView)findViewById(R.id.edit_pullvalue_Pertain)).setText(curPertain);
                btn_pullvalue_AddLine.setText("添加行");
                btn_pullvalue_AddLine.setBackgroundColor(getResources().getColor(R.color.text_orange));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            edit_pullvalue_BowlNo.requestFocus();
        }
        if (parent==pullList)
        {
            curPullListPosition=position;
        }

    }
    private void clearPullData(){
        mainDB.execSQL("delete from PullCloth");
        try {
            pullJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        PullListAdapter pullListAdapter=new PullListAdapter(getApplicationContext());
        pullList.setAdapter(pullListAdapter);
        showClothFootTotal();
    }
    private String getLevelNo(){
        String tmpLevelNo="1";
        Cursor cur = mainDB.rawQuery("Select ifnull(Max(LevelNo),0) LevelNo from PullCloth", null);
        if (cur.getCount() > 0) {
            cur.moveToFirst();
            tmpLevelNo=String.valueOf(cur.getInt(cur.getColumnIndex("LevelNo"))+1);
        } else tmpLevelNo="1";
        cur.close();
        return tmpLevelNo;
    }
    //增加行;
    private void addLine(final int position,final boolean append){
        try {
            String BowlNo="";
            if (edit_pullvalue_BowlNo.getText().toString().length()>0) BowlNo=edit_pullvalue_BowlNo.getText().toString();
            System.out.println("AddLine---------------------------------------------------------------------");
            if (edit_pullvalue_LevelNum.getText().length()==0){
                curToast.setText("请输入层数!");
                curToast.show();
                return;
            }
            if (edit_pullvalue_Color.getText().toString().length()==0){
                curToast.setText("请选择拉布颜色!");
                curToast.show();
                return;
            }
            if (append==false) {
                pullJson.getJSONObject(position).put("BowlNo", BowlNo);
                if (edit_pullvalue_IdentLen.getText().length() > 0)
                    pullJson.getJSONObject(position).put("IdentLen", edit_pullvalue_IdentLen.getText());
                else pullJson.getJSONObject(position).put("IdentLen", "0");
                if (edit_pullvalue_LevelNum.getText().length() > 0)
                    pullJson.getJSONObject(position).put("LevelNum", edit_pullvalue_LevelNum.getText());
                else pullJson.getJSONObject(position).put("LevelNum", "0");
                if (edit_pullvalue_PrepNum.getText().length() > 0)
                    pullJson.getJSONObject(position).put("PrepNum", edit_pullvalue_PrepNum.getText());
                else pullJson.getJSONObject(position).put("PrepNum", "0");
                if (edit_pullvalue_RollNum.getText().length() > 0)
                    pullJson.getJSONObject(position).put("RollNum", edit_pullvalue_RollNum.getText());
                else pullJson.getJSONObject(position).put("RollNum", "0");
                if (edit_pullvalue_OwenLen.getText().length() > 0)
                    pullJson.getJSONObject(position).put("OwenLen", edit_pullvalue_OwenLen.getText());
                else pullJson.getJSONObject(position).put("OwenLen", "0");
                if (edit_pullvalue_PullPeople.getText().length() > 0)
                    pullJson.getJSONObject(position).put("PullPeople", edit_pullvalue_PullPeople.getText());
                else pullJson.getJSONObject(position).put("PullPeople", "");
                if (chk_PullTypeB.isChecked())
                    pullJson.getJSONObject(position).put("PullType", "Auto");
                else pullJson.getJSONObject(position).put("PullType", "Hand");
                mainDB.execSQL("UPDATE  PullCloth set BowlNo=?,IdentLen=?,LevelNum=?,PrepNum=?,RollNum=?,OwenLen=?,ClothBarcode=?,PullPeople=?,PullType=? where ProduceCutDeID=? ",
                        new Object[]{pullJson.optJSONObject(position).getString("BowlNo")
                                , pullJson.optJSONObject(position).getString("IdentLen"), pullJson.optJSONObject(position).getString("LevelNum")
                                , pullJson.optJSONObject(position).getString("PrepNum"), pullJson.optJSONObject(position).getString("RollNum")
                                , pullJson.optJSONObject(position).getString("OwenLen")
                                ,pullJson.optJSONObject(position).getString("PullPeople")
                                ,pullJson.optJSONObject(position).getString("PullType")
                                ,curClothBarcode, pullJson.optJSONObject(position).getString("ProduceCutDeID")});
                //更新到表格列表;
                ((BaseAdapter)pullList.getAdapter()).notifyDataSetChanged();
            } else
            {
                JSONObject tmpJson=new JSONObject();
                tmpJson.put("LevelNo",curLevelNo);
                tmpJson.put("ProduceCutDeID",curProduceCutDeID);
                tmpJson.put("ProduceDetailID",curProduceDetailID);
                tmpJson.put("ProduceCutMaID", ProduceCutMaID);
                tmpJson.put("Color", curColor);
                tmpJson.put("ColorNo", curColorNo);
                tmpJson.put("Pertain", curPertain);
                tmpJson.put("BowlNo", BowlNo);
                if (edit_pullvalue_IdentLen.getText().length() > 0) tmpJson.put("IdentLen", edit_pullvalue_IdentLen.getText());else tmpJson.put("IdentLen", "0");
                if (edit_pullvalue_LevelNum.getText().length() > 0) tmpJson.put("LevelNum", edit_pullvalue_LevelNum.getText());else tmpJson.put("LevelNum", "0");
                if (edit_pullvalue_PrepNum.getText().length() > 0) tmpJson.put("PrepNum", edit_pullvalue_PrepNum.getText());else tmpJson.put("PrepNum", "0");
                if (edit_pullvalue_RollNum.getText().length() > 0) tmpJson.put("RollNum", edit_pullvalue_RollNum.getText());else tmpJson.put("RollNum", "0");
                if (edit_pullvalue_OwenLen.getText().length() > 0) tmpJson.put("OwenLen", edit_pullvalue_OwenLen.getText());else tmpJson.put("OwenLen", "0");
                if (edit_pullvalue_ShortLen.getText().length() > 0) tmpJson.put("ShortLen", edit_pullvalue_ShortLen.getText());else tmpJson.put("ShortLen", "0");
                if (edit_pullvalue_PullPeople.getText().length() > 0) tmpJson.put("PullPeople", edit_pullvalue_PullPeople.getText());else tmpJson.put("PullPeople", "");
                if (chk_PullTypeB.isChecked()) tmpJson.put("PullType", "Auto");
                else tmpJson.put("PullType", "Hand");
                if (curClothBarcode.length() > 0) tmpJson.put("ClothBarcode", curClothBarcode);else tmpJson.put("ClothBarcode", "UNKNOW");
                JSONArray tmppulljson=new JSONArray();
                tmppulljson.put(tmpJson);
                for (int i=0;i<pullJson.length();i++){
                    tmppulljson.put(pullJson.optJSONObject(i));
                }
                pullJson=tmppulljson;
                System.out.println("addLine--insert");
                //保存到数据库里
                mainDB.execSQL("INSERT INTO PullCloth(LevelNo,ProduceCutDeID,ProduceDetailID,ProduceCutMaID,ColorNo,Color,Pertain,BowlNo,IdentLen,LevelNum,PrepNum,RollNum,ShortLen,OwenLen,PullPeople,PullType,ClothBarcode) " +
                                "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                        new Object[]{tmpJson.getString("LevelNo"), tmpJson.getString("ProduceCutDeID")
                                , tmpJson.getString("ProduceDetailID"), tmpJson.getString("ProduceCutMaID")
                                , tmpJson.getString("ColorNo"), tmpJson.getString("Color")
                                , tmpJson.getString("Pertain"), tmpJson.getString("BowlNo")
                                , tmpJson.get("IdentLen"), tmpJson.get("LevelNum")
                                , tmpJson.get("PrepNum"), tmpJson.get("RollNum"), tmpJson.get("ShortLen"), tmpJson.get("OwenLen"),tmpJson.get("PullPeople"),tmpJson.get("PullType"),tmpJson.get("ClothBarcode")});
                //通过适配器显示;
                System.out.println(pullJson);
                PullListAdapter pullListAdapter=new PullListAdapter(getApplicationContext());
                pullList.setAdapter(pullListAdapter);
            }
            //获取新行号;
            curLevelNo=getLevelNo();
            curProduceCutDeID= UUID.randomUUID().toString();
            setActiveEdt(edit_ClothBarcode);
            //((TextView)findViewById(R.id.edit_pullvalue_Color)).setText("");
            //((TextView)findViewById(R.id.edit_pullvalue_ColorNo)).setText("");
            //((TextView)findViewById(R.id.edit_pullvalue_Pertain)).setText("");
            //edit_pullvalue_BowlNo.setText("");
            edit_pullvalue_IdentLen.setText("");
            edit_pullvalue_LevelNum.setText("");
            //edit_pullvalue_PrepNum.setText("");//门幅
            //edit_pullvalue_RollNum.setText("");//段长
            edit_pullvalue_OwenLen.setText("");
            edit_pullvalue_ShortLen.setText("");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //显示汇总页脚
        showClothFootTotal();
        hideIM(edit_pullvalue_BowlNo);
    }



    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //显示汇总页脚;
    private void showClothFootTotal() {
        Cursor cur = mainDB.rawQuery("Select sum(IdentLen) IdentLen,sum(LevelNum) LevelNum,sum(PrepNum) PrepNum,sum(RollNum) RollNum,sum(ShortLen) ShortLen,sum(OwenLen) OwenLen from PullCloth", null);
        if (cur.getCount() > 0) {
            cur.moveToFirst();
            TextView txt_item_IdentLen = findViewById(R.id.txt_foot_IdentLen);
            txt_item_IdentLen.setText(cur.getString(cur.getColumnIndex("IdentLen")));
            TextView txt_item_LevelNum=findViewById(R.id.txt_foot_LevelNum);
            txt_item_LevelNum.setText(cur.getString(cur.getColumnIndex("LevelNum")));
            TextView txt_item_OwenLen=findViewById(R.id.txt_foot_OwenLen);
            txt_item_OwenLen.setText(cur.getString(cur.getColumnIndex("OwenLen")));
            TextView txt_item_ShortLen=findViewById(R.id.txt_foot_ShortLen);
            txt_item_ShortLen.setText(cur.getString(cur.getColumnIndex("ShortLen")));
        }
    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("PullActivity----onStart");
    }

    @Override
    public void onPause() {
        super.onPause();
        stopMusic();
        System.out.println("PullActivity----onPause");
    }

    /**
     * 创建网络mp3
     * @return
     */
    public MediaPlayer createNetMp3(){
        String url=curServiceDir+"/warn.mp3";
        System.out.println("音乐文件地址："+url);
        MediaPlayer mp=new MediaPlayer();
        try {
            mp.setDataSource(url);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (IllegalStateException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return mp;
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

        return false;
    }

    //订单表格适配器;
    public final class ColorListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ColorListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return colorJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return colorJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.pull_colorlist_item, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (colorJson.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = colorJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv =  convertView.findViewById(R.id.txt_item_Color);// 显示文字
                if (colorJson.optJSONObject(position).has("Color")==true)
                    tv.setText(colorJson.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                if (colorJson.optJSONObject(position).has("ColorNo")==true)
                    tv.setText(colorJson.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_Pertain);// 显示文字
                if (colorJson.optJSONObject(position).has("Pertain")==true)
                    tv.setText(colorJson.optJSONObject(position).get("Pertain").toString());
                tv.setTextColor(color);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","ColorListAdapter_position:"+position);
            return convertView;
        }
    }


    //订单表格适配器;
    public final class PullListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public PullListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return pullJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return pullJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.pull_right_clothhead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()a----------------------------------------------------->"+position);
                if (pullJson.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = pullJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv =  convertView.findViewById(R.id.txt_item_Color);// 显示文字
                if (pullJson.optJSONObject(position).has("Color")==true)
                    tv.setText(pullJson.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                if (pullJson.optJSONObject(position).has("ColorNo")==true)
                    tv.setText(pullJson.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_Pertain);// 显示文字
                if (pullJson.optJSONObject(position).has("Pertain")==true)
                    tv.setText(pullJson.optJSONObject(position).get("Pertain").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_BowlNo);// 显示文字
                if (pullJson.optJSONObject(position).has("BowlNo")==true)
                    tv.setText(pullJson.optJSONObject(position).get("BowlNo").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_IdentLen);// 显示文字
                if (pullJson.optJSONObject(position).has("IdentLen")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("IdentLen").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_LevelNum);// 显示文字
                if (pullJson.optJSONObject(position).has("LevelNum")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("LevelNum").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_DoorWidth);// 显示文字
                if (pullJson.optJSONObject(position).has("PrepNum")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("PrepNum").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_SectionLen);// 显示文字
                if (pullJson.optJSONObject(position).has("RollNum")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("RollNum").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_OwenLen);// 显示文字
                if (pullJson.optJSONObject(position).has("OwenLen")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("OwenLen").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_ShortLen);// 显示文字
                if (pullJson.optJSONObject(position).has("ShortLen")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("ShortLen").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_PullPeople);// 显示文字
                if (pullJson.optJSONObject(position).has("PullPeople")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("PullPeople").toString()));
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","PullListAdapter_position:"+position);
            return convertView;
        }
    }

    //插放音乐;
    private void playMusic(){
        try {
            if(mediaPlayer==null) {
                mediaPlayer = createNetMp3();
                mediaPlayer.setLooping(false);
                //在播放音频资源之前，必须调用Prepare方法完成些准备工作
                mediaPlayer.prepare();
            }
            if(mediaPlayer!=null) {
                if (mediaPlayer.isPlaying()==false) mediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //停止播放音乐
    private  void  stopMusic(){
        if(mediaPlayer!=null){
            mediaPlayer.stop();//停止播放
            mediaPlayer.release();//释放资源
            mediaPlayer=null;
        }
    }

}
